#! /bin/awk -f
# Author : Raman Rawat
# renames the input file/dir as per the replacement strings
#  Variables   r() and Replacement are passed as "-v r=XXXX Replacement=YYYY"
#  

BEGIN {
nFiles=0
}

{
#print "length of " $1 "is" length($1) 
# if(NR > 10) {
# exit 0
# }

if( length($1) > 0) {

	#z=r
	#print "z = "z
	#gsub(/?/, /\\?/, z)
	#print "After rep z = "z
	cmd  = "sed " r " " $1 " > " $1".tmp"
	print cmd
	system(cmd)
	
	x="mv " $1".tmp " $1
	system(x)
	
    # make the new file name
    z=$3
    #gsub(r, Replacement, z)
    #print "z =" z
    
    #move the file to the new name.
    if (z != $3) {
        # append dir seperator
    	newPath=$2"/"z
    	
    	# Check if file already exists
    	"file " newPath | getline line
    	
    	#print "File status of " $1 " : " 
    	if( index(line, "No such file or directory") > 0 ||
    		index(line, "directory") > 0 ) {
    	# Move the dir to new name
		x="mv " $1 " " newPath
		} else {		
    	# 
		x="cat -s"  newPath " >> " $1  
		}
		
		# print the cmd along with num
		print "[" nFiles++ "] " x
		system(x)
    }
 }
}
END {
}
